import { encrypt, decrypt } from "@/util/crypot";
const storage = window.localStorage;

function getStoreItem(key: string) {
  const value = storage.getItem(encrypt(key));
  if (value) {
    return JSON.parse(decrypt(value));
  } else {
    if (storage.getItem(encrypt(key + "_ExpiredTime"))) {
      const expiredTimeValue = decrypt(
        storage.getItem(encrypt(key + "_ExpiredTime")) as string
      );
      if (
        new Date().getTime() - Number(expiredTimeValue.split("_")[1]) >
        import.meta.env.VITE_APP_LOCAL_EXPIRED_TIME
      ) {
        // 过期了
        removeStoreItem(key + "_ExpiredTime");
        return null;
      } else {
        return JSON.parse(expiredTimeValue.split("_")[0]);
      }
    }
  }
  return null;
}

function setStoreItem(key: string, val: any, hasExpiredTime = false) {
  let value = JSON.stringify(val);
  if (hasExpiredTime) {
    key = `${key}_ExpiredTime`;
    value = `${value}_${new Date().getTime()}`;
  }
  storage.setItem(encrypt(key), encrypt(value));
}

function removeStoreItem(key: string | Array<string>) {
  if (typeof key === "string") {
    storage.removeItem(encrypt(key));
  } else {
    key.forEach(item => {
      storage.removeItem(encrypt(item));
    });
  }
}

// 保存聊天主题
function saveUserChatTheme(userId: number, chatId: string, themeId: string) {
  const key = `chat_theme_${userId}_${chatId}`;
  setStoreItem(key, themeId);
}

// 获取聊天主题
function getUserChatTheme(userId: number, chatId: string): string {
  const key = `chat_theme_${userId}_${chatId}`;
  const themeId = getStoreItem(key);
  return themeId || "default"; // 默认主题
}

export { 
  getStoreItem, 
  setStoreItem, 
  removeStoreItem,
  saveUserChatTheme,
  getUserChatTheme
};
